// packageC/video_goods/releaseVideo/releaseVideo.js
var app = getApp();
const GoodsByidUrl = "plugin.store-alone-temp.frontend.videoShare.goods.getGoodsById";
const subTapUrl = "plugin.store-alone-temp.frontend.videoShare.video.sub";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    plu_options: {
      default_title: true
    },
    language: '',
    myvideo: '',
    goods_id: '',
    title: "",
    videoUrl: "",
    isVideo: true,
    realVideo: "",
    coverUrl: "",
    duration: 0, //视频时长
    chooseGoods: null, //商品信息
    videoPath: "", //视频链接参数
    videoCover: "", //封面图片参数
    limit: 60, //视频限制时长
    uploadIng: false, //正在上传中
    videoProgress: 0,
    showUploadBtn: false, //是否显示确认上传按钮引导用户上传（解决ios无法自动播放）
    imguploadIng: false,
    isNeedGoods: true, //是否开启选择商品
    background:'',
    checked: true,
    protocol_content: '',
    showAgreement: false,
    theme_color:'#000',
    showGoods:false,
    goods_id:'',

    categoryList: [],
    categoryFilterList: [],
    category_id: null,
    category_name: "",
    showCategory: false,
    searchWord: "",
    is_show_cate: false,
    imgPath: app.globalData.imgPath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.myvideo = wx.createVideoContext('myvideo');
    this.init();
    this.getPermission();

    try {
      var value = wx.getStorageSync('shareVideoPath');
      if (value) {
        let shareVideoPath = JSON.parse(value);
        if (shareVideoPath.title) {
          this.setData({
            title: shareVideoPath.title
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl,
            videoPath: shareVideoPath.videoUrl
          });
        }
        if (shareVideoPath.videoCover) {
          this.setData({
            videoCover: shareVideoPath.videoCover
          });
        }
        if (shareVideoPath.category_id) {
          this.setData({
            category_id: shareVideoPath.category_id
          });
        }
        if (shareVideoPath.category_name) {
          this.setData({
            category_name: shareVideoPath.category_name
          });
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    // if (options.goods_id) {
    //   this.setData({
    //     goods_id: options.goods_id
    //   });
    //   this.getGoodsById();
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      theme_color:basic_info.theme_color
    })
    console.log(this.data.theme_color)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  closeChooseGoods(e){
    this.setData({showGoods:false})
    if(e.detail.goods_id == this.data.goods_id || !e.detail.goods_id) return
    this.setData({
      goods_id : e.detail.goods_id
    })
    this.getGoodsById();
  },
  init() {
    this.setData({
      title: '',
      videoUrl: '',
      isVideo: true,
      duration: 0,
      chooseGoods: null,
      videoCover: '',
      limit: '',
      uploadIng: false,
      showUploadBtn: false,
      coverUrl: '',
      realVideo: '',
      videoPath: '',
      isNeedGoods: true
    });
  },
  getBackground(){
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.set.getBackground");
    app._getNetWork({
      url: urlStr,
      data: {
        validate_page: 1
      }, // validate_page 实名认证判断
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            background: res.data.background
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getList() {
    //获取限制时长
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.set.getLimit");
    app._getNetWork({
      url: urlStr,
      data: {
        validate_page: 1
      }, // validate_page 实名认证判断
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let {is_show_cate,select_goods,limit,...other} = res.data;

          this.setData({
            is_show_cate: is_show_cate == "1" ? true : false,
            isNeedGoods: select_goods == 1 ? true : false,
            plu_options: other
          });
          if (!app._isTextEmpty(limit)) {
            this.setData({
              limit: res.data.limit
            });
          }
          if(!other.notice) {
            this.setData({
              ['plu_options.notice']: `温馨提示:视频时长不应超过${ limit }秒，封面图尽量和视频高度一致`
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //验证会员发布权限
  getPermission() {
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.permission.verify");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          if (!res.data.ret) {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: res.msg,
              success (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1,
                    success: function () {
                      setTimeout(() => {
                        wx.showToast({
                          title: res.msg,
                          icon: 'none',
                          duration: 1500
                        });
                      }, 1000);
                    },
                    fail: ()=>{
                      wx.reLaunch({
                        url: '/packageG/index/index'
                      })
                    }
                  });
                }
              }
            })
            return;
          }
          this.getList();
          this.getBackground();
          this.getAgreement();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getGoodsById() {
    let that = this;
    let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1?GoodsByidUrl:"plugin.video-share.frontend.goods.getGoodsById");
    app._getNetWork({
      url: urlStr,
      data: {
        goods_id: this.data.goods_id
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            chooseGoods: res.data.goods
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onReadVideo() {
    let that = this;
    //iOS中选择上传视频不能超过60秒
    // wx.chooseVideo({
    //   sourceType: ['album', 'camera'],
    //   maxDuration: 60,
    //   camera: 'back',
    //   compressed:false,
    //   success(res) {
    //     that.getDuration(res.duration, res.tempFilePath);
    //     that.setData({
    //       videoUrl: res.tempFilePath
    //     });
    //   }
    // });
    // wx.chooseVideo 获取不到视频缩略图
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success(res) {
        that.getDuration(res.tempFiles[0]);
      }
    })
  },

  getDuration(_Files) {
    let basic_info = wx.getStorageSync("yz_basic_info");
    let {upload_max_file_size} = basic_info;
    let _max = 100;//php配置最大文件上传大小
    if(upload_max_file_size) _max = upload_max_file_size/1024/1024;
    if(_Files.size/1024/1024 > _max ){
      app.tips(`视频大小超出${_max}M，请压缩后上传！`);
      this.resetVideo();
      return;
    }
    //获取视频或者音频时长
    this.data.duration = _Files.duration;
    if (this.data.duration < 1) {
      this.resetVideo();
      app.tips("视频时长太短了！！");
      return;
    } 
    if (this.data.limit && this.data.duration > Number(this.data.limit) + 1) {
      this.resetVideo();
      app.tips(`视频时长不能超过${this.data.limit}秒`);
      return;
    } 

    this.setSrcAndCaptureImage(_Files.tempFilePath);
    this.data.coverUrl = _Files.thumbTempFilePath;
    this.uploadImageM(); //上传封面 -----------------
    this.setData({
      videoUrl: _Files.tempFilePath
    });
  },
  resetVideo(){
    // 重置视频地址
    this.setData({
      videoUrl: null
    });
  },
  setSrcAndCaptureImage(videoData) {
    this.data.realVideo = videoData;
    if (this.data.realVideo) {
      this.setData({
        videoUrl: null
      });
    }
    this.uploadAudioM(); //上传视频 --------------
  },
  uploadAudioM() {
    let that = this;
    //视频上传
    that.setData({
      uploadIng: true
    });
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.upload.uploadAudio");
    urlStr += '&3rd_session=' + session;
    wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.data.realVideo,
      name: 'file',
      formData: {},
      header: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success(res) {
        var resData = JSON.parse(res.data);
        if (resData.result == 1) {
          that.data.videoPath = resData.data.audio;
          that.data.file_name = resData.data.file_name;
          that.setData({
            uploadIng: false,
            videoPath: resData.data.audio,
            file_name: resData.data.file_name
          });
          //本地保存标题、视频链接--------------
          let hasData = {
            title: (that.data.title ? that.data.title : ''),
            videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
            videoCover: (that.data.videoCover ? that.data.videoCover : ''),
            file_name: (that.data.file_name ? that.data.file_name : '')
          };
          try {
            wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
          } catch (e) {
            console.log(e);
          }
        } else {
          that.setData({
            videoUrl: null,
            isVideo: true,
            duration: 0,
            videoCover: '',
            limit: '',
            uploadIng: false,
            showUploadBtn: false
          });
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 2500
          });
        }
      }
    });
  },
  uploadImageM() {
    //图片上传
    let that = this;
    that.setData({
      imguploadIng: true
    });
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.data.coverUrl,
      name: 'file',
      formData: {},
      success(res) {
        var resData = JSON.parse(res.data);
        if (resData.result == 1) {
          that.setData({
            videoCover: resData.data.img_url
          });
          //本地保存标题、视频链接--------------
          let hasData = {
            title: (that.data.title ? that.data.title : ''),
            videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
            videoCover: (that.data.videoCover ? that.data.videoCover : '')
          };
          try {
            wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
          } catch (e) {
            console.log(e);
          }
          that.setData({
            imguploadIng: false
          });
        } else {
          that.setData({
            imguploadIng: false
          });
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 1500
          });
        }
      }
    });
  },
  BtnMethos() {
    let that = this;
    if (this.data.isNeedGoods && app._isTextEmpty(this.data.chooseGoods)) {
      //商品为空，则跳转到商品搜索页添加商品
      //本地保存标题、视频链接--------------
      let hasData = {
        title: (that.data.title ? that.data.title : ''),
        videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
        videoCover: (that.data.videoCover ? that.data.videoCover : ''),
        file_name: (that.data.file_name ? that.data.file_name : ''),
        category_id: (that.data.category_id ? that.data.category_id : ''),
        category_name: (that.data.category_name ? that.data.category_name : '')
      };
      try {
        wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
      } catch (e) {
        console.log(e);
      }
      this.setData({
        showGoods:true
      })
    } else {
      if(!this.data.checked){
        app.tips('请勾选用户协议');
        return
      }
      //商品不为空，而且视频、标题已添加，则进行发布
      if (!this.data.plu_options.default_title && app._isTextEmpty(this.data.title)) {
        wx.showToast({
          title: "请输入4-18个字标题",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      if (this.data.plu_options.must_video && app._isTextEmpty(this.data.videoUrl)) {
        wx.showToast({
          title: "请选择视频进行上传！",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.videoCover)) {
        wx.showToast({
          title: "请选择一张图片作为视频封面图！",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      let file = wx.getStorageSync('shareVideoPath');
      file = JSON.parse(file);
      let json = {
        goods_id: this.data.goods_id,
        title: this.data.title,
        video: this.data.videoPath,
        cover: this.data.videoCover,
        file_name: this.data.file_name ? this.data.file_name : file.file_name
      };

      if (this.data.is_show_cate) {
        json.category_id = this.data.category_id || 0;
      }

      let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1?subTapUrl:"plugin.video-share.frontend.video.sub");
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            try {
              wx.removeStorageSync('shareVideoPath');
            } catch (e) {
              // Do something when catch error
            }

            let _url = '/packageC/video_goods/VideoList/VideoList';
            if(this.options.from == 'validate') _url = 'packageG/index/index';
            wx.navigateTo({
              url: _url
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        }
      });
    }
  },
  titleBlur(event) {
    let val = event.detail.value;
    if (val.length < 4) {
      wx.showToast({
        icon: 'none',
        title: '请输入不小于4个字',
        duration: 1500
      });
      return;
    }
    this.setData({
      title: val
    });
  },
  gotoAdd() {
    // wx.navigateTo({
    //   url: '/packageC/video_goods/addVideoGood/addVideoGood'
    // });
    this.setData({
      showGoods:true
    })
  },
  onReadimge() {
    let that = this;
    if (that.data.imguploadIng) {
      wx.showToast({
        icon: 'none',
        title: '图片正在上传请勿点击',
        duration: 1500
      });
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.data.coverUrl = tempFilePaths[0];
        that.uploadImageM(); //上传封面 -----------------
      }
    });
  },
  getCategory() {
    if (this.data.categoryList.length > 0) {
      this.setData({
        showCategory: true
      });
      return;
    }

    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.video.getCategory");
    app._getNetWork({
      url: urlStr,
      data: {
        is_select: 1
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            categoryList: res.data,
            categoryFilterList: res.data,
            showCategory: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onFilterCategory(e) {
    if (e.type == 'change') {
      this.setData({
        searchWord: e.detail
      });
    }

    if (this.data.searchWord == "") {
      this.setData({
        categoryFilterList: this.data.categoryList
      });
      return;
    }
    if (this.data.categoryList.find(obj => obj.name == this.data.searchWord)) {
      let arr = new Array(this.data.categoryList.find(obj => obj.name == this.data.searchWord));
      this.setData({
        categoryFilterList: arr
      });
      return;
    } else {
      this.setData({
        categoryFilterList: this.data.categoryList
      });
      return;
    }
  },
  onClickCategory(e) {
    console.log(e.currentTarget.dataset);
    this.setData({
      category_id: e.currentTarget.dataset.id,
      category_name: e.currentTarget.dataset.name,
      showCategory: false
    });
  },
  onClose() {
    this.setData({
      showCategory: false,
      showGoods:false,
    });
  },
  agreementbtn(e){
    this.setData({
      checked : e.detail
    })
  },
  removeImg(e) {
    let _tag = e.currentTarget.dataset.tag;
    var value = wx.getStorageSync('shareVideoPath');
    value = JSON.parse(value)
    if (_tag == "img") {
      value.videoCover = null;
      this.setData({
        videoCover: null,
        images: []
      })
    } else if (_tag == "video") {
      value.videoUrl = null;
      value.videoPath = null;
      this.setData({
        videoUrl: null,
        videoPath: null
      })
    }
    wx.setStorageSync('shareVideoPath', JSON.stringify(value))
  },
  gotoAgreement() {
    this.setData({
      showAgreement: true
    });
  },
  popClose() {
    this.setData({
      showAgreement: false
    });
  },
  getAgreement() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.set.getAgreement");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            protocol_content: res.data.agreement
          });
        } else {
          that.setData({
            protocol_content: res.msg
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
});